<template>
  <div class="image-upload-container">
    <!-- 上传区域 -->
    <div 
      class="upload-area"
      :class="{ 'is-dragover': isDragOver, 'is-disabled': disabled }"
      @drop="handleDrop"
      @dragover="handleDragOver"
      @dragenter="handleDragEnter"
      @dragleave="handleDragLeave"
      @click="triggerFileInput"
    >
      <input
        ref="fileInput"
        type="file"
        :accept="accept"
        :multiple="multiple"
        @change="handleFileSelect"
        style="display: none;"
        :disabled="disabled"
      />
      
      <div class="upload-content">
        <el-icon class="upload-icon" :size="48">
          <Plus />
        </el-icon>
        <div class="upload-text">
          <p>点击或拖拽图片到此区域上传</p>
          <p class="upload-hint">支持 {{ acceptText }}，单个文件不超过 {{ maxSizeText }}</p>
        </div>
      </div>
    </div>

    <!-- 上传进度 -->
    <div v-if="uploading" class="upload-progress">
      <el-progress :percentage="uploadProgress" :show-text="false" />
      <span class="progress-text">上传中... {{ uploadProgress }}%</span>
    </div>

    <!-- 图片预览列表 -->
    <div v-if="imageList.length > 0" class="image-list">
      <div 
        v-for="(image, index) in imageList" 
        :key="index"
        class="image-item"
      >
        <div class="image-wrapper">
          <img :src="image.url" :alt="image.alt" @click="previewImage(image)" />
          <div class="image-actions">
            <el-button 
              type="primary" 
              size="small" 
              circle
              @click="previewImage(image)"
            >
              <el-icon><View /></el-icon>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              circle
              @click="removeImage(index)"
              :disabled="disabled"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="image-info">
          <p class="image-name">{{ image.alt }}</p>
          <p class="image-size" v-if="image.size">{{ formatFileSize(image.size) }}</p>
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="80%"
      center
    >
      <div class="preview-container">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, defineEmits, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, View, Delete } from '@element-plus/icons-vue'
import { uploadImage, uploadImages, deleteImage } from '@/api/upload'

const props = defineProps({
  // 是否支持多选
  multiple: {
    type: Boolean,
    default: false
  },
  // 最大文件大小 (MB)
  maxSize: {
    type: Number,
    default: 5
  },
  // 接受的文件类型
  accept: {
    type: String,
    default: 'image/*'
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 初始图片列表
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'success', 'error'])

// 响应式数据
const fileInput = ref()
const isDragOver = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const imageList = ref([...props.modelValue])
const previewVisible = ref(false)
const previewImageUrl = ref('')

// 计算属性
const acceptText = computed(() => {
  const types = props.accept.split(',').map(type => type.trim())
  return types.join(', ')
})

const maxSizeText = computed(() => {
  return `${props.maxSize}MB`
})

// 触发文件选择
const triggerFileInput = () => {
  if (!props.disabled) {
    fileInput.value?.click()
  }
}

// 处理文件选择
const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  handleFiles(files)
  // 清空input值，允许重复选择同一文件
  event.target.value = ''
}

// 处理拖拽相关事件
const handleDragOver = (event) => {
  event.preventDefault()
}

const handleDragEnter = (event) => {
  event.preventDefault()
  if (!props.disabled) {
    isDragOver.value = true
  }
}

const handleDragLeave = (event) => {
  event.preventDefault()
  isDragOver.value = false
}

const handleDrop = (event) => {
  event.preventDefault()
  isDragOver.value = false
  
  if (props.disabled) return
  
  const files = Array.from(event.dataTransfer.files).filter(file => 
    file.type.startsWith('image/')
  )
  
  if (files.length > 0) {
    handleFiles(files)
  }
}

// 处理文件上传
const handleFiles = async (files) => {
  // 验证文件
  const validFiles = files.filter(file => {
    if (file.size > props.maxSize * 1024 * 1024) {
      ElMessage.error(`文件 ${file.name} 超过大小限制`)
      return false
    }
    return true
  })

  if (validFiles.length === 0) return

  try {
    uploading.value = true
    uploadProgress.value = 0

    let uploadResult
    if (props.multiple && validFiles.length > 1) {
      // 批量上传
      uploadResult = await uploadImages(validFiles)
    } else {
      // 单个上传
      uploadResult = await uploadImage(validFiles[0])
    }

    uploadProgress.value = 100

    if (uploadResult.code === 1) {
      const newImages = Array.isArray(uploadResult.data) 
        ? uploadResult.data 
        : [uploadResult.data]
      
      if (props.multiple) {
        imageList.value.push(...newImages)
      } else {
        imageList.value = newImages
      }
      
      emit('update:modelValue', imageList.value)
      emit('success', newImages)
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(uploadResult.msg || '上传失败')
      emit('error', uploadResult.msg)
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error('上传失败')
    emit('error', error.message)
  } finally {
    uploading.value = false
    uploadProgress.value = 0
  }
}

// 移除图片
const removeImage = async (index) => {
  try {
    const image = imageList.value[index]
    
    // 调用删除接口
    const result = await deleteImage(image.url)
    
    if (result.code === 1) {
      imageList.value.splice(index, 1)
      emit('update:modelValue', imageList.value)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除错误:', error)
    ElMessage.error('删除失败')
  }
}

// 预览图片
const previewImage = (image) => {
  previewImageUrl.value = image.url
  previewVisible.value = true
}

// 格式化文件大小
const formatFileSize = (size) => {
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  
  return `${Math.round(size * 100) / 100} ${units[unitIndex]}`
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  imageList.value = [...newValue]
}, { deep: true })
</script>

<style scoped>
.image-upload-container {
  width: 100%;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover:not(.is-disabled) {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.upload-area.is-dragover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.upload-area.is-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.upload-icon {
  color: #8c939d;
}

.upload-text p {
  margin: 0;
  color: #606266;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
}

.upload-progress {
  margin-top: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-text {
  font-size: 14px;
  color: #606266;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.image-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  background-color: white;
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 120px;
  overflow: hidden;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.image-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-wrapper:hover .image-actions {
  opacity: 1;
}

.image-info {
  padding: 8px;
}

.image-name {
  font-size: 12px;
  color: #606266;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-size {
  font-size: 11px;
  color: #909399;
  margin: 4px 0 0 0;
}

.preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-area {
    padding: 20px;
  }
  
  .image-list {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
  }
  
  .image-wrapper {
    height: 100px;
  }
}
</style>
